#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File    :   manual_operation.py
@Time    :   2023/04/08 09:38:08
@Author  :   youle
@Email   :   a_fly0505@163.com
@Copyright : 侵权必究
'''

from core.config import Config, g_config
from stock.stock_hist import StockHist
from stock.clear_datas import ClearDatas
from technicalindicator.indicators import Indicators
from server.server import Server

from model.db_operator import MarketFundOperator, FundOperator, g_fund_op, g_market_fund_op
import model.db_operator as dbOperator
import model.db_models as dbModel

#debug
import logging
import sys
import datetime
import psycopg2
import akshare as ak
import pandas as pd
import numpy as np
import core.utils as utils
import json

clearDatas = ClearDatas(g_config)

#sync stock
stock_hist = StockHist(g_config)

# server RSI
server = Server(g_config)

################################################
def ClearMarket():
    clearDatas.ClearStockDatas()
    clearDatas.ClearMarket()


################################################
def SyncStockHist():
    stock_hist.InitDB()
    # stock_hist.GetAllStockInfo()
    stock_hist.GetAllStockHist()
    # stock_hist.DeleteStockByDay("2023-03-29")

################################################
def TableInit():
    fund_etf_df = ak.fund_etf_spot_em()
    fundCodes=[]
    funds=[]
    for item in fund_etf_df.values:
        code:str = item[0]
        sname = item[1]
        funds.append(dbModel.MarketFunc(code=code, sname=sname))
        fundCodes.append(code)

    g_market_fund_op.Insert(funds)
    #创建所有的etf表
    g_fund_op.CreateAllTables(fundCodes)
    g_fund_op.DropAllTables(fundCodes)

################################################
def RunStockRSI():
    # Stock RSI
    stock_hist.SyncStockEveryDay()
    print("=== begin compute stock RSI ===")
    codes = server.GetStockRSI(thres=25.0, last=1, timeperiod=14)
    print(json.dumps(codes, ensure_ascii=False))

################################################
def RunFundRSI():
    # Fund RSI
    server.SyncFundEveryDay()
    print("=== begin compute fund RSI ===")
    codes = server.GetFundRSI(thres=33.0, last=1, timeperiod=14)
    print(json.dumps(codes, ensure_ascii=False))
    

################################################
def GetFundHist():
    funds = g_market_fund_op.QueryAll()
    for fund in funds:
        print(fund.code, fund.sname)
        fund_etf_hist_df = ak.fund_etf_hist_em(
            symbol=fund.code, period="daily", start_date="20000101", end_date="20230501", adjust="")
        fund_datas = []
        FundObject =  g_market_fund_op.GetFundTable(fund.code)
        for item in fund_etf_hist_df.values:
            fundItem = FundObject(date=item[0], open=item[1], close=item[2], hight=item[3], low=item[4], volume=item[5],
                                  volume_quota=item[6], vibration=item[7], rise_fall_rate=item[8], rise_fall_quota=item[9], turnover_rate=item[10])
            fund_datas.append(fundItem)
        g_fund_op.InsertList(fund.code, fund_datas)

################################################
def SyncFundHist():
    now = datetime.datetime.now()
    today = now.date()
    funds = g_market_fund_op.QueryAll()
    for fund in funds:
        code: str = fund.code
        sname: str = fund.sname
        FundObject = g_market_fund_op.GetFundTable(code)
        fund_obj = g_fund_op.QueryLastDay(FundObject)
        lastDate:datetime.date = fund_obj.date
        # 是否只隔了一个工作日
        isOneDay = utils.IsOneDay(today, lastDate)
        if not isOneDay:
            # 大于一个工作日，查询历史数据，如数据库
            # 历史数据开始的日期
            begin_date = lastDate+datetime.timedelta(days=1)
            end_date = today+datetime.timedelta(days=1)
            print("get fund:{}:{} begin begin_date:{}, end_date{}".format(code, sname, begin_date, end_date))
            server.UpdateFund(code, beginDate=begin_date, endDate=end_date)
        else:
            print("===================")

################################################
if __name__ == '__main__':
    utils.LogConfig()
    dbModel.Init(g_config)

    # ClearMarket()
    # sys.exit(0)

    # SyncStockHist()

    # dbOperator.CreateAllTable()

    # SyncFundHist()

    RunFundRSI()

    # RunStockRSI()
    


